import pymssql
from src.config import Config,LoggerConfig
import logging

LoggerConfig.configure_logger('log/sn-audit-report.log')
logging = logging.getLogger('Base')

class Base:
    def __init__(self):
        # 初始化配置和数据库连接属性
        self.config = Config()
        self.database_config = self.config.get_database_config()
        self.database = self.config.NAME
        self.connection = None

    def connect(self):
        """
        建立与数据库的连接
        """
        try:
            self.connection = pymssql.connect(
                server=self.database_config['host'],
                user=self.database_config['user'],
                password=self.database_config['password'],
                database=self.database,
                port=self.database_config['port']
            )
        except pymssql.OperationalError as e:
            logging.error(f"连接失败: {e}")
            self.connection = None

    def close(self):
        """
        关闭与数据库的连接
        """
        if self.connection:
            self.connection.close()
            logging.info("连接关闭")
            self.connection = None

    def execute_query(self, query, params=None):
        """
        执行SQL查询
        :param query: 要执行的SQL查询语句
        :param params: SQL查询的参数
        :return: 返回查询的游标
        """
        if not self.connection:
            self.connect()
        if self.connection:
            cursor = self.connection.cursor(as_dict=True)
            cursor.execute(query, params or ())
            return cursor

    def commit(self):
        """
        提交当前事务
        """
        if self.connection:
            self.connection.commit()
